<?php

include_once ROOT_PATH.'web/lib/pdd/ddk.class.php';

class api_pinduoduo {
    public $page = 1;
    public $sum = 0;
    private $page_size = 100;


    private $rate = 50;
    private $rate_higher = 50;
    private $rate_superior = 50;

    private $pdd_goods_table;
    private $pdd_goods_table_grab;

    private $SUPER_INFO = array();
    private $SHOPER_INFO = array();
    private $SALER_INFO = array();
    private $SERVICER_INFO = array();

    private $ddk;

    public function __construct() {
        global $_G;
        $this->ddk = new ddk();

        $order_setting = DB::fetch_first("SELECT * FROM " . DB::table('pdd_order_setting') . " WHERE `name` = 'all'");
        if (!empty($order_setting)) {
            $this->rate = $order_setting['rate'];
            $this->rate_higher = $order_setting['rate_higher'];
            $this->rate_superior = $order_setting['rate_superior'];
        }
        $order_setting_vip = DB::fetch_first("SELECT `rate` FROM " . DB::table('pdd_order_setting')  . " WHERE `name` = 'vip'");
        $this->pdd_goods_table = DB::result_first("SELECT `value` FROM " . DB::table('setting') . " WHERE `name` = 'pdd_goods_table'");
        $this->pdd_goods_table_grab = DB::result_first("SELECT `value` FROM " . DB::table('setting') . " WHERE `name` = 'pdd_goods_table_grab'");

        // 超级会员分佣信息
        $this->SUPER_INFO = DB::fetch_first("SELECT * FROM " . DB::table('x_group') . " WHERE `type` = 'super'");

        // 店主分佣信息
        $this->SHOPER_INFO = DB::fetch_first("SELECT * FROM " . DB::table('x_group') . " WHERE `type` = 'shoper'");

        // 销售经理分佣信息
        $this->SALER_INFO = DB::fetch_first("SELECT * FROM " . DB::table('x_group') . " WHERE `type` = 'saler'");

        // 服务经理分佣信息
        $this->SERVICER_INFO = DB::fetch_first("SELECT * FROM " . DB::table('x_group') . " WHERE `type` = 'servicer'");
    }

    public function update_perfect() {
        ignore_user_abort(); // 后台运行
        set_time_limit(0); // 取消脚本运行时间的超时上限
        ini_set('memory_limit',-1); // 不限制最大内存

        logResult('pdd_update_perfect', "精选商品检查[BEGIN]");

        // 更新精选商品表
        $perfect_goods = DB::fetch_all("SELECT `goods_id`, `goods_name` FROM " . DB::table('pdd_perfect_goods') . " WHERE `has_coupon` = 1 AND `status` = 1");
        if (!empty($perfect_goods)) {
            foreach ($perfect_goods as $k => $v) {
                $goods_id = $v['goods_id'];
                $goods_name = $v['goods_name'];
                $goods_promotion_url = $this->ddk->get_goods_promotion_url(
                    array('p_id' => '230009_11162249',
                        'goods_id_list' => $goods_id,
                        'generate_short_url' => 'false',
                    )
                );

                if (!$goods_promotion_url) {
                    logResult('pdd_update_perfect', "精选商品goods_id: " . $goods_id . ", goods_name: " . $goods_name . " 过期了做删除处理");

                    DB::update('pdd_perfect_goods', array('status' => 0, 'update_at' => TIMESTAMP), array('goods_id' => $goods_id));
                }
            }
        }

        logResult('pdd_update_perfect', "精选商品检查[END]");
    }

    public function get_cats() {
        ignore_user_abort(); // 后台运行
        set_time_limit(0); // 取消脚本运行时间的超时上限
        ini_set('memory_limit', -1); // 不限制最大内存

        $result = $this->ddk->get_goods_cats(
            array('parent_cat_id' => 0)
        );
        if (!empty($result)) {
            foreach ($result as $k => $data) {
                $level = $data['level'];
                $cat_id = $data['cat_id'];
                $data=$this->filter_file('pdd_cats',$data);
                $check = DB::fetch_first("SELECT `id` FROM " . DB::table('pdd_cats') . " WHERE `level` = " . $level . " AND `cat_id` = " . $cat_id);
                if (!empty($check) && $check['id'] > 0) {
                    DB::update('pdd_cats', $data, array('id' => $check['id']));
                } else {
                    DB::insert('pdd_cats', $data);
                }
            }
        }
    }

    /*public function update_again() {
        ignore_user_abort(); // 后台运行
        set_time_limit(0); // 取消脚本运行时间的超时上限
        ini_set('memory_limit',-1); // 不限制最大内存


        $del_success = 0;
        $update_success = 0;
        $off_success = 0;
        $rs = DB::fetch_all("SELECT goods_id, coupon_end_time FROM " . DB::table('pdd_goods'));
        if (!empty($rs)) {
             foreach ($rs as $k => $v) {
                 $goods_id = $v['goods_id'];
                 $goods_details = $this->get_detail($goods_id);
                 if (is_array($goods_details)) {
                     if (empty($goods_details)) { // 商品标记为删除
                        $r = DB::update('pdd_goods', array('status' => -1, 'update_at' => TIMESTAMP), "goods_id='" . $goods_id . "'");
                        if ($r > 0) {
                            $del_success++;
                        }
                     } else {
                         $goods_detail = $goods_details[0];
                         $update['goods_desc'] = $goods_detail['goods_desc'];
                         $goods_gallery_urls = $goods_detail['goods_gallery_urls'];
                         if (!empty($goods_gallery_urls)) {
                             $goods_gallery_urls = array_filter($goods_gallery_urls);
                             $update['goods_gallery_urls'] = implode(',', $goods_gallery_urls);
                         }
                         $update['update_at'] = TIMESTAMP;

                         $r = DB::update('pdd_goods', $update, "goods_id='" . $goods_id . "'");
                         if ($r > 0) {
                             $update_success++;
                         }
                     }
                 }

                 $coupon_end_time = $v['coupon_end_time'];
                 if ($coupon_end_time <= TIMESTAMP) {
                     // 商品标记为下架
                     $r = DB::update('pdd_goods', array('status' => 0, 'update_at' => TIMESTAMP), "goods_id='" . $goods_id . "'");
                     if ($r > 0) {
                         $off_success++;
                     }
                 }

                 sleep(1); // 停留1秒
             }
        }

        $msg = '补充检查完毕，将' . $del_success . '个商品标记为删除，将' . $off_success . '个商品标记为下架，将' . $update_success . '个商品更新了详情';
        logResult('pdd_update_again', $msg);
    }*/

    public function update_theme() {
        logResult("pdd_get_theme_goods", "拼多多主题商品抓取[BEGIN]");

        DB::query("TRUNCATE TABLE " . DB::table('pdd_theme')); // 清空表

        $page = 1;
        $page_size = 50;
        while (true) {
            $theme_list = $this->ddk->get_theme(
                array(
                    'page_size' => $page_size, // 1~50
                    'page' => $page // 1~10000
                )
            );
            if (!$theme_list) {
                break;
            }

            foreach ($theme_list as $k => $v) {
                $theme_id = $v['id'];
                $check_theme = DB::fetch_first("SELECT `id` FROM " . DB::table('pdd_theme') . " WHERE `theme_id` = " . $theme_id);
                if (!empty($check_theme) && $check_theme['id'] > 0) {
                    $r = DB::update('pdd_theme',
                        array(
                            'image_url' => $v['image_url'],
                            'name' => $v['name'],
                            'goods_num' => $v['goods_num'],
                            'goods' => '',
                            'update_at' => TIMESTAMP
                        ),
                        array('theme_id' => $theme_id));
                } else {
                    $r = DB::insert('pdd_theme',
                        array(
                            'theme_id' => $theme_id,
                            'image_url' => $v['image_url'],
                            'name' => $v['name'],
                            'goods_num' => $v['goods_num'],
                            'goods' => '',
                            'create_at' => TIMESTAMP,
                            'update_at' => TIMESTAMP
                        ),
                        1
                    );
                }

                if ($r > 0) {
                    logResult("pdd_get_theme_goods", json_encode($v, JSON_UNESCAPED_UNICODE));
                } else {
                    logResult("pdd_get_theme_goods_err", json_encode($v, JSON_UNESCAPED_UNICODE));
                }

                $goods_arr = array();
                $result = $this->ddk->theme_goods_search(array('theme_id' => $theme_id));
                if ($result) {
                    $goods_list = $this->parse_theme_goods($result);
                    if (!empty($goods_list)) {
                        foreach ($goods_list as $gk => $data) {
                            $cat_ids = $data['cat_ids']; // "cat_ids": [77, 4365, 4418, 0]
                            if (!empty($cat_ids)) {
                                $data['cat_ids'] = implode(',', $data['cat_ids']);
                            } else {
                                unset($data['cat_ids']);
                            }

                            $opt_ids = $data['opt_ids'];
                            if (!empty($opt_ids)) {
                                $data['opt_ids'] = implode(',', $data['opt_ids']);
                            } else {
                                unset($data['opt_ids']);
                            }

                            $data['status'] = 1;

                            $goods_id = $data['goods_id'];
                            $check = DB::fetch_first("SELECT `id` FROM " . DB::table($this->pdd_goods_table_grab) . " WHERE `goods_id` = '" . $goods_id . "'");
                            $data=$this->filter_file($this->pdd_goods_table_grab,$data);
                            if (!empty($check) && $check['id'] > 0) {
                                $data['update_at'] = TIMESTAMP;
                                $tr = DB::update($this->pdd_goods_table_grab, $data, array('goods_id' => $goods_id));
                            } else {
                                $data['create_at'] = TIMESTAMP;
                                $data['update_at'] = TIMESTAMP;
                                $tr = DB::insert($this->pdd_goods_table_grab, $data, 1);
                            }

                            $goods_arr[] = $goods_id;
                        }
                    }
                }

                if (!empty($goods_arr)) {
                    $goods = implode(',', $goods_arr);
                    DB::update('pdd_theme',
                        array('goods' => $goods, 'update_at' => TIMESTAMP),
                        array('theme_id' => $theme_id)
                    );
                }
            }

            $page++;
        }

        logResult("pdd_get_theme_goods", "拼多多主题商品抓取[END]");
    }

    public function auto_update() {
        ignore_user_abort(); // 后台运行
        set_time_limit(0); // 取消脚本运行时间的超时上限
        ini_set('memory_limit', -1); // 不限制最大内存

        logResult('pdd_get_goods', "拼多多商品抓取[BEGIN]");

        $pdd_goods_grabbing = DB::result_first("SELECT `value` FROM " . DB::table('setting') . " WHERE `name` = 'pdd_goods_grabbing'");
        if ('1' == $pdd_goods_grabbing) return;

        DB::update('setting', array('value' => '1'), "`name` = 'pdd_goods_grabbing'");

        DB::delete($this->pdd_goods_table_grab, '1 = 1');
        DB::query("ALTER TABLE " . DB::table($this->pdd_goods_table_grab) . " AUTO_INCREMENT = 1");

        $this->sum = 0;
        while (true) {
            $goods_list = $this->get();
            if (!$goods_list) {
                break; // 跳出循环
            }

            $success = $this->update($goods_list);
            $this->sum += $success;

            $msg = '正在抓取第' . $this->page . '页，本页成功处理' . $success . '条，总共成功处理' . $this->sum . '条';
            logResult('pdd_get_goods', $msg);

            $this->page++;

            sleep(1); // 停留1秒
        }

        $this->update_theme(); // 抓取主题商品

        if ($this->sum > 0) {
            DB::update('setting', array('value' => $this->pdd_goods_table_grab), "`name` = 'pdd_goods_table'");
            DB::update('setting', array('value' => $this->pdd_goods_table), "`name` = 'pdd_goods_table_grab'");

            $this->pdd_goods_table = DB::result_first("SELECT `value` FROM " . DB::table('setting') . " WHERE `name` = 'pdd_goods_table'");
            $this->pdd_goods_table_grab = DB::result_first("SELECT `value` FROM " . DB::table('setting') . " WHERE `name` = 'pdd_goods_table_grab'");

            DB::delete($this->pdd_goods_table_grab, '1 = 1');
            DB::query("ALTER TABLE " . DB::table($this->pdd_goods_table_grab) . " AUTO_INCREMENT = 1");
        }

        DB::update('setting', array('value' => '0'), "`name` = 'pdd_goods_grabbing'");

        $msg = '抓取完毕，总共成功处理' . $this->sum . '条';
        logResult('pdd_get_goods', $msg);

        logResult('pdd_get_goods', "拼多多商品抓取[END]");
        echo $msg;
    }
   /* 处理数组里多余字段开始*/
    public  function  filter_file($table_name,$data){
        $data_keys=array_keys($data);

        $table_file=DB::fetch_all("select column_name from Information_schema.columns  where table_Name ='".DB::table($table_name)."' and TABLE_SCHEMA='yspdd'");
       foreach($table_file as $k=>$v){
           $arr[]=$v['column_name'];
       }
        foreach($data_keys as $key =>$value){
           if(!in_array($value,$arr)){

            unset($data[$value]);
           }
        }
        return $data;
        }




   /* 处理数组里多余字段结束*/
   private function update($goods_list) {
        if (empty($goods_list)) return 0;

        $success = 0;
        foreach ($goods_list as $k => $data) {
            $cat_ids = $data['cat_ids']; // "cat_ids": [77, 4365, 4418, 0]
            if (!empty($cat_ids)) {
                $data['cat_ids'] = implode(',', $data['cat_ids']);
            } else {
                unset($data['cat_ids']);
            }

            $opt_ids = $data['opt_ids'];
            if (!empty($opt_ids)) {
                $data['opt_ids'] = implode(',', $data['opt_ids']);
            } else {
                unset($data['opt_ids']);
            }

            $data['status'] = 1;

            $goods_id = $data['goods_id'];
            $check = DB::fetch_first("SELECT `id` FROM " . DB::table($this->pdd_goods_table_grab) . " WHERE `goods_id` = '" . $goods_id . "'");
           $data=$this->filter_file($this->pdd_goods_table_grab,$data);
            if (!empty($check) && $check['id'] > 0) {
                $data['update_at'] = TIMESTAMP;
                $r = DB::update($this->pdd_goods_table_grab, $data, array('goods_id' => $goods_id));
            } else {
                $data['create_at'] = TIMESTAMP;
                $data['update_at'] = TIMESTAMP;
                $r = DB::insert($this->pdd_goods_table_grab, $data, 1);
            }

            if ($r > 0) {
                $success++;
            } else {
                logResult('pdd_get_goods_err', "goods_id: " . $data['goods_id'] . ", goods_name: " . $data['goods_name']);
            }
        }

        return $success;
    }

    private function get() {
        $result = $this->ddk->goods_search(
            array(
                'page' => $this->page,
                'page_size' => $this->page_size,
                'sort_type' => 0,
                'with_coupon' => 'true'
            )
        );

        return $this->parse_goods($result);

        // sort_type 排序方式：0-综合排序；1-按佣金比率升序；2-按佣金比例降序；3-按价格升序；4-按价格降序；5-按销量升序；6-按销量降序；7-优惠券金额排序升序；8-优惠券金额排序降序；9-券后价升序排序；10-券后价降序排序；11-按照加入多多进宝时间升序；12-按照加入多多进宝时间降序
        // with_coupon
    }

    private function parse_goods($result) {
        if ($result) {
            $arr = json_decode($result, true);
            if (!empty($arr)
                && array_key_exists('goods_search_response', $arr)
                && array_key_exists('goods_list', $arr['goods_search_response'])) {
                $rs = $arr['goods_search_response']['goods_list'];
                foreach ($rs as $k => $v) {
                    $goods_id = $v['goods_id'];
                    $goods_details = $this->get_detail($goods_id);
                    if (!empty($goods_details)) {
                        $goods_detail = $goods_details[0];
                        $rs[$k]['goods_desc'] = $goods_detail['goods_desc'];
                        $goods_gallery_urls = $goods_detail['goods_gallery_urls'];
                        if (!empty($goods_gallery_urls)) {
                            $goods_gallery_urls = array_filter($goods_gallery_urls);
                            $rs[$k]['goods_gallery_urls'] = implode(',', $goods_gallery_urls);
                        }
                    }
                }

                return $rs;
            }
        }

        return false;
    }

    private function parse_theme_goods($result) {
        if ($result) {
            $arr = json_decode($result, true);
            if (!empty($arr)
                && array_key_exists('theme_list_get_response', $arr)
                && array_key_exists('goods_list', $arr['theme_list_get_response'])) {
                $rs = $arr['theme_list_get_response']['goods_list'];
                foreach ($rs as $k => $v) {
                    $goods_id = $v['goods_id'];
                    $goods_details = $this->get_detail($goods_id);
                    if (!empty($goods_details)) {
                        $goods_detail = $goods_details[0];
                        $rs[$k]['goods_desc'] = $goods_detail['goods_desc'];
                        $goods_gallery_urls = $goods_detail['goods_gallery_urls'];
                        if (!empty($goods_gallery_urls)) {
                            $goods_gallery_urls = array_filter($goods_gallery_urls);
                            $rs[$k]['goods_gallery_urls'] = implode(',', $goods_gallery_urls);
                        }
                    }
                }

                return $rs;
            }
        }

        return false;
    }

    public function get_goods($goods_id, $table) {
        // 抓取单个商品

        if (!empty($goods_id)) {
            $result = $this->ddk->goods_search(
                array(
                    'page' => $this->page,
                    'page_size' => $this->page_size,
                    'sort_type' => 0,
                    'with_coupon' => 'true',
                    'goods_id_list' => '[' . $goods_id . ']'
                )
            );

            if ($result) {
                $goods_list = $this->parse_goods($result);
                foreach ($goods_list as $k => $data) {
                    $has_coupon = $data['has_coupon'];
                    if ($has_coupon) {
                        $cat_ids = $data['cat_ids']; // "cat_ids": [77, 4365, 4418, 0]
                        if (!empty($cat_ids)) {
                            $data['cat_ids'] = implode(',', $data['cat_ids']);
                        } else {
                            unset($data['cat_ids']);
                        }

                        $opt_ids = $data['opt_ids'];
                        if (!empty($opt_ids)) {
                            $data['opt_ids'] = implode(',', $data['opt_ids']);
                        } else {
                            unset($data['opt_ids']);
                        }

                        $data['status'] = 1;

                        $goods_id = $data['goods_id'];
                        $check = DB::fetch_first("SELECT `id` FROM " . DB::table($table) . " WHERE `goods_id` = '" . $goods_id . "'");
                        $data=$this->filter_file($table,$data);
                        if (!empty($check) && $check['id'] > 0) {
                            $data['update_at'] = TIMESTAMP;
                            $r = DB::update($table, $data, array('goods_id' => $goods_id));
                        } else {
                            $data['create_at'] = TIMESTAMP;
                            $data['update_at'] = TIMESTAMP;
                            $r = DB::insert($table, $data, 1);
                        }

                        if ($r > 0) {
                            logResult('pdd_get_1_goods', "单个商品抓取成功 goods_id: " . $data['goods_id'] . ", goods_name: " . $data['goods_name']);
                        } else {
                            logResult('pdd_get_1_goods_err', "goods_id: " . $data['goods_id'] . ", goods_name: " . $data['goods_name']);
                        }
                    }
                }
            }
        }
    }

    public function get_cat_goods() {
        ignore_user_abort(); // 后台运行
        set_time_limit(0); // 取消脚本运行时间的超时上限
        ini_set('memory_limit', -1); // 不限制最大内存

        logResult('get_cat_goods', "抓取所有类目的商品[BEGIN]");

        DB::query("TRUNCATE TABLE " . DB::table('pdd_cat_goods')); // 清空表

        $goods_cats = DB::fetch_all("SELECT `cat_id`, `cat_name` FROM " . DB::table('pdd_cats') . " WHERE `parent_cat_id` = 0");
        if (!empty($goods_cats)) {
            foreach ($goods_cats as $k => $v) {
                $cat_id = $v['cat_id'];
                $cat_name = $v['cat_name'];

                $page = 1;
                $page_size = $this->page_size;
                while (true) {
                    $goods_list = $this->get_goods_by_cat_id($cat_id, $page, $page_size);
                    if (!$goods_list) {
                        break; // 跳出循环
                    }

                    $success = $this->update_cat_goods($goods_list);

                    $msg = '[商品类目: ' . $cat_name . ']正在抓取第' . $page . '页，本页成功处理' . $success . '条';
                    logResult('get_cat_goods', $msg);

                    $page++;

                    sleep(1); // 停留1秒
                }
            }
        }

        logResult('get_cat_goods', "抓取所有类目的商品[END]");
    }

    private function update_cat_goods($goods_list) {
        if (empty($goods_list)) return 0;

        $success = 0;
        foreach ($goods_list as $k => $data) {
            $cat_ids = $data['cat_ids']; // "cat_ids": [77, 4365, 4418, 0]
            if (!empty($cat_ids)) {
                $data['cat_ids'] = implode(',', $data['cat_ids']);
            } else {
                unset($data['cat_ids']);
            }

            $opt_ids = $data['opt_ids'];
            if (!empty($opt_ids)) {
                $data['opt_ids'] = implode(',', $data['opt_ids']);
            } else {
                unset($data['opt_ids']);
            }

            $data['status'] = 1;

            $goods_id = $data['goods_id'];
            $check = DB::fetch_first("SELECT `id` FROM " . DB::table('pdd_cat_goods') . " WHERE `goods_id` = '" . $goods_id . "'");
            $data=$this->filter_file('pdd_cat_goods',$data);
            if (!empty($check) && $check['id'] > 0) {
                $data['update_at'] = TIMESTAMP;
                $r = DB::update('pdd_cat_goods', $data, array('goods_id' => $goods_id));
            } else {
                $data['create_at'] = TIMESTAMP;
                $data['update_at'] = TIMESTAMP;
                $r = DB::insert('pdd_cat_goods', $data, 1);
            }

            if ($r > 0) {
                $success++;
            } else {
                logResult('get_cat_goods_err', "goods_id: " . $data['goods_id'] . ", goods_name: " . $data['goods_name']);
            }
        }

        return $success;
    }

    private function get_goods_by_cat_id($cat_id, $page, $page_size) {
        $result = $this->ddk->goods_search(
            array(
                'page' => $page,
                'page_size' => $page_size,
                'sort_type' => 0,
                'with_coupon' => 'true',
                'cat_id' => $cat_id
            )
        );

        return $this->parse_goods($result);
    }

    public function get_detail($goods_id) {
        $result = $this->ddk->goods_detail($goods_id);
        if ($result) {
            $arr = json_decode($result, true);
            if (!empty($arr)
                && array_key_exists('goods_detail_response', $arr)
                && array_key_exists('goods_details', $arr['goods_detail_response'])) {

                return $arr['goods_detail_response']['goods_details'];
            }
        }

        return false;
    }

    public function get_p_id() {
        return $this->ddk->get_p_id();
    }

    public function get_goods_promotion_url($p_id, $goods_id, $generate_we_app = false) {
        $cachename = 'goods_promotion_url_' . $p_id . '_' . $goods_id;
        $goods_promotion_url = memory('get', $cachename);
        if (!$goods_promotion_url) { // 过期了
            $option = array('p_id' => $p_id,
                'goods_id_list' => $goods_id,
                'generate_short_url' => 'true',
                'multi_group' => 'false'
            );
            if ($generate_we_app) {
                $option['generate_we_app'] = 'true';
            }

            $goods_promotion_url = $this->ddk->get_goods_promotion_url(
                $option
            );

            if ($goods_promotion_url) {
                memory('set', $cachename, $goods_promotion_url, 12 * 3600);
            }
        }

        return $goods_promotion_url;
    }

    public function get_theme_prom_url($p_id, $theme_id, $generate_we_app = false) {
        $cachename = 'theme_prom_url_' . $p_id . '_' . $theme_id;
        $theme_prom_url = memory('get', $cachename);
        if (!$theme_prom_url) { // 过期了
            $option = array(
                'p_id' => $p_id,
                'theme_id_list' => '[' . $theme_id . ']',
                'generate_short_url' => 'true',
                'generate_mobile' => 'true'
            );
            // TODO 生成小程序的推广URL

            $theme_prom_url = $this->ddk->get_theme_prom_url($option);
            if ($theme_prom_url) {
                memory('set', $cachename, $theme_prom_url, 12 * 3600);
            }
        }

        return $theme_prom_url;
    }

    public function get_cms_prom_url($p_id, $generate_we_app = false) {
        $cachename = 'cms_prom_url_' . $p_id;
        $cms_prom_url = memory('get', $cachename);
        if (!$cms_prom_url) { // 过期了
            $option = array(
                'generate_short_url' => 'true',
                'p_id_list' => '["' . $p_id . '"]',
                'generate_mobile' => 'true'
            );
            // TODO 生成小程序的推广URL

            $cms_prom_url = $this->ddk->get_cms_prom_url($option);
            if ($cms_prom_url) {
                memory('set', $cachename, $cms_prom_url, 12 * 3600);
            }
        }

        return $cms_prom_url;
    }

    public function get_rp_prom_url($p_id) {
        $cachename = 'rp_prom_url_' . $p_id;
        $rp_prom_url = memory('get', $cachename);
        if (!$rp_prom_url) { // 过期了
            $option = array(
                'generate_short_url' => 'true',
                'p_id_list' => '["' . $p_id . '"]'
            );

            $rp_prom_url = $this->ddk->get_rp_prom_url($option);
            if ($rp_prom_url) {
                memory('set', $cachename, $rp_prom_url, 12 * 3600);
            }
        }

        return $rp_prom_url;
    }

    public function get_act_prom_url($p_id) {
        $cachename = 'act_prom_url_' . $p_id;
        $act_prom_url = memory('get', $cachename);
        if (!$act_prom_url) { // 过期了
            $option = array(
                'url_type' => 1,
                'generate_short_url' => 'true',
                'generate_mobile_short_url' => 'true',
                'p_id_list' => '["' . $p_id . '"]'
            );

            $act_prom_url = $this->ddk->get_act_prom_url($option);
            if ($act_prom_url) {
                memory('set', $cachename, $act_prom_url, 12 * 3600);
            }
        }

        return $act_prom_url;
    }
     //只拉今天

    public function today_update_order() {
        ignore_user_abort(); // 后台运行
        set_time_limit(0); // 取消脚本运行时间的超时上限
        ini_set('memory_limit', -1); // 不限制最大内存

        $begin_last_today = time(); // 今天以内  // modify by LiuPeng 2018-09-11
        $end_last_today = time();

        $start_time = date('Y-m-d', $begin_last_today);
      $start_time2=$start_time." 00:00";
      $start_time2=strtotime($start_time);
        $end_time2 =$start_time2+24*3600;
       $end_time=date('Y-m-d',$end_time2);
        $start_update_time = $start_time2;
        $end_update_time = $end_time2;
        logResult('today_pdd_get_order', "拼多多今日推广订单同步[BEGIN] 开始日期: " . $start_time . " 结束日期: " . $end_time);



                //$this->order_get($p_id, $start_time, $end_time);
                $this->order_increment_get($start_update_time, $end_update_time);



        logResult('today_pdd_get_order', "拼多多今日推广订单同步[END] 开始日期: " . $start_time . " 结束日期: " . $end_time);

   }

   public function many_update_order(){
       ignore_user_abort(); // 后台运行
       set_time_limit(0); // 取消脚本运行时间的超时上限
       ini_set('memory_limit', -1); // 不限制最大内存

       $begin_last_today = time(); // 今天以内  // modify by LiuPeng 2018-09-11
       $end_last_today = time();

       $start_time = date('Y-m-d', $begin_last_today);
       $start_time2=$start_time." 00:00";
       $start_time2=strtotime($start_time);
       $end_time2 =$start_time2+24*3600;
       $end_time=date('Y-m-d',$end_time2);
       $start_update_time = $start_time2;
       $end_update_time = $end_time2;
       $start=$_GET['start'];
       $size=$_GET['size'];

               $this->order_increment_get($start_update_time, $end_update_time);

   }


    public function update_order() {
        ignore_user_abort(); // 后台运行
        set_time_limit(0); // 取消脚本运行时间的超时上限
        ini_set('memory_limit', -1); // 不限制最大内存

        //$beginThisMonth = mktime(0,0,0,date('m'),1,date('Y'));
        //$endThisMonth = mktime(23,59,59,date('m'),date('t'),date('Y'));

        //$begin_last_90_day = time() - 90 * 24 * 3600; // 90天以内
        $begin_last_90_day = time() - 30 * 24 * 3600; // 30天以内  // modify by LiuPeng 2018-09-11
        $end_last_90_day = time();

        $start_time = date('Y-m-d', $begin_last_90_day);
        $end_time = date('Y-m-d', $end_last_90_day);
        $start_update_time = $begin_last_90_day;
        $end_update_time = $end_last_90_day;

        logResult('pdd_get_order', "拼多多推广订单同步[BEGIN] 开始日期: " . $start_time . " 结束日期: " . $end_time);

        $this->order_increment_get($start_update_time, $end_update_time);

                sleep(1);



        logResult('pdd_get_order', "拼多多推广订单同步[END] 开始日期: " . $start_time . " 结束日期: " . $end_time);
    }

    public  function update_order_pid($p_id) {
        //$begin_last_90_day = time() - 90 * 24 * 3600; // 90天以内
        $begin_last_90_day = time() - 30 * 24 * 3600; // 30天以内 // modify by LiuPeng 2018-09-11
        $end_last_90_day = time();

        $start_time = date('Y-m-d', $begin_last_90_day);
        $end_time = date('Y-m-d', $end_last_90_day);
        $start_update_time = $begin_last_90_day;
        $end_update_time = $end_last_90_day;
        logResult('pdd_get_order_pid', "拼多多推广订单同步[BEGIN] 开始日期: " . $start_time . " 结束日期: " . $end_time);
        $this->order_increment_get($p_id,$start_update_time, $end_update_time);
        logResult('pdd_get_order_pid', "拼多多推广订单同步[END] 开始日期: " . $start_time . " 结束日期: " . $end_time);
    }

    private function order_increment_get($start_update_time, $end_update_time) {
        $page = 1;
        $page_size = $this->page_size;
        while (true) {
            $order_list = $this->ddk->get_increment_order_list(
                array(
                    'start_update_time' => $start_update_time, // 时间戳
                    'end_update_time' => $end_update_time, // 时间戳
                    'page' => $page,
                    'page_size' => $page_size
                )
            );
            if (!$order_list) {
                break;
            }

            $this->parse_order($order_list);

            $page++;
            sleep(1);
        }
    }

    private function order_get($p_id, $start_time, $end_time) {
        $page = 1;
        $page_size = $this->page_size;

        while (true) {
            $order_list = $this->ddk->get_range_order_list(
                array(
                    'p_id' => $p_id,
                    'start_time' => $start_time,
                    'end_time' => $end_time,
                    'page' => $page,
                    'page_size' => $page_size
                )
            );

            if (!$order_list) {
                break;
            }

            $this->parse_order($p_id, $order_list);

            $page++;
            sleep(1);
        }
    }

    private function parse_order($order_list)
    {
        if (!empty($order_list)) {
            foreach ($order_list as $k => $data) {
                // 直推者
                $p_id = $data['p_id'];
                $member = DB::fetch_first("SELECT `uid`, `money`, `t_uid`, `vip`, `vip_expire` FROM " . DB::table('member') . " WHERE p_id = '" . $p_id . "' AND LENGTH(p_id) > 0");
                if (!empty($member) && $member['uid'] > 1) {


                    if (!empty($member) && (intval($member['t_uid']) > 0)) {
                        $t_uid = $member['t_uid']; // 直推者的直接上级
                        $higher_member = DB::fetch_first("SELECT `uid`, `money`, `t_uid` FROM " . DB::table('member') . " WHERE uid = " . $t_uid . " AND ((p_id IS NOT NULL) AND (LENGTH(p_id) > 0))");
                        if (!empty($higher_member) && (intval($higher_member['t_uid'])) > 0) {
                            $h_t_uid = $higher_member['t_uid']; // 直推者的直接上级的直接上级
                            $superior_member = DB::fetch_first("SELECT `uid`, `money`, `t_uid` FROM " . DB::table('member') . " WHERE uid = " . $h_t_uid . " AND ((p_id IS NOT NULL) AND (LENGTH(p_id) > 0))");
                        }
                    }
                    $vip = $member['vip'];
                    $vip_expire = $member['vip_expire'];
                    if ($vip_expire < TIMESTAMP) {
                        $vip = 0;
                    }
                    if (1 == $vip) {
                        $order_setting = DB::fetch_first("SELECT * FROM " . DB::table('pdd_order_setting') . " WHERE `name` = 'vip'");
                        if (!empty($order_setting)) {
                            $this->rate = $order_setting['rate'];
                            $this->rate_higher = $order_setting['rate_higher'];
                            $this->rate_superior = $order_setting['rate_superior'];
                        }
                    }


                    $order_sn = $data['order_sn'];
                    $order_create_time = $data['order_create_time'];
                    $order_status = intval($data['order_status']);

                    $status = 0;
                    if ($order_status == 5) { // 已经结算
                        $status = 1; // 可以提现
                    }

                    // 订单状态：0-已支付；1-已成团；2-确认收货；3-审核成功；4-审核失败（不可提现）;-1 待支付
                    // 已经成团的订单产生的佣金就可以提现了
                    // ys_pdd_order_promotion 表中的status字段 1-可以提现；2-已申请结算；3-审核成功；4-审核失败；5-已结算
                    $data = $this->filter_file('pdd_order_list', $data);
                    $check = DB::fetch_first("SELECT `id` FROM " . DB::table('pdd_order_list') . " WHERE order_sn = '" . $order_sn . "'");
                    if (!empty($check) && $check['id'] > 0) {
                        $data['update_at'] = TIMESTAMP;
                        DB::update('pdd_order_list', $data, "order_sn = '" . $order_sn . "' AND p_id = '" . $p_id . "'");

                        if ($order_status != 8) {
                            $order_id = $check['id'];
                            if (1 == $status) {
                                $p_members = DB::fetch_all("SELECT `p_uid`, `promotion_amount` FROM " . DB::table('pdd_order_promotion') . " WHERE `order_id` = " . $order_id . " AND `type` <> 'system' AND `status` < 1");
                                if (!empty($p_members)) {
                                    foreach ($p_members as $pk => $pm) {
                                        DB::query("UPDATE " . DB::table('member') . " SET `money` = `money` + " . $pm['promotion_amount'] . " WHERE `uid` = " . $pm['p_uid']);
                                    }
                                }
                            }

                            DB::update('pdd_order_promotion', array('status' => $status, 'update_at' => TIMESTAMP), "`order_id` = " . $order_id . " AND `status` < 1");
                        }
                    } else {
                        $data['create_at'] = TIMESTAMP;
                        $data['update_at'] = TIMESTAMP;
                        $r = DB::insert('pdd_order_list', $data, 1);

                        if ($order_status != 8) {
                            $order_id = $r;
                            $promotion_amount_total = $data['promotion_amount']; // 这一笔订单总的佣金 // 10元
                            $promotion_amount_direct = $promotion_amount_total * $this->rate / 100; // 直推者的佣金 // 6元
                            $promotion_amount_higher = ($promotion_amount_total - $promotion_amount_direct) * $this->rate_higher / 100; // 直推者上级的佣金 // 2元
                            $promotion_amount_superior = ($promotion_amount_total - $promotion_amount_direct - $promotion_amount_higher) * $this->rate_superior / 100; // 直推者上级的上级的佣金 // 1元

                            $promotion_amount_direct = pdd_fix($promotion_amount_direct / 100, 2) * 100; // 单位是分
                            $promotion_amount_higher = pdd_fix($promotion_amount_higher / 100, 2) * 100; // 单位是分
                            $promotion_amount_superior = pdd_fix($promotion_amount_superior / 100, 2) * 100; // 单位是分

                            if (!empty($member)) {
                                DB::insert('pdd_order_promotion',
                                    array(
                                        'order_id' => $order_id,
                                        'p_id' => $p_id,
                                        'type' => 'direct',
                                        'p_uid' => $member['uid'],
                                        'promotion_amount' => $promotion_amount_direct,
                                        'order_create_time' => $order_create_time,
                                        'status' => $status,
                                        'create_at' => TIMESTAMP,
                                        'update_at' => TIMESTAMP
                                    ),
                                    1);

                                if (1 == $status) { // 佣金可提现
                                    //DB::update('member', array('money' => $member['money'] + $promotion_amount_direct), "uid=" . $member['uid']);
                                    DB::query("UPDATE " . DB::table('member') . " SET `money` = `money` + " . $promotion_amount_direct . " WHERE `uid` = " . $member['uid']);
                                }

                                if (1 == $vip) {
                                    // 系统额外补贴 system_pension
                                    $hot_goods = DB::fetch_first("select b.hot_expire as hot_expire,b.pension as pension,b.hot as hot from " . DB::table("pdd_order_list") . " as a left join " . DB::table("pdd_hot_goods") . " as b  on  a.goods_id=b.goods_id where a.p_id='" . $p_id . "'");
                                    if (!empty($hot_goods) && isset($hot_goods)) {
                                        if ($hot_goods['hot_expire'] < TIMESTAMP) {
                                            $hot_goods['hot'] = 0;
                                        }
                                        $hot = $hot_goods['hot'];
                                        $pension = $hot_goods['pension'];
                                    }
                                    if ($hot == 1) {
                                        DB::insert('pdd_order_promotion',
                                            array(
                                                'order_id' => $order_id,
                                                'p_id' => $p_id,
                                                'type' => 'system_pension',
                                                'p_uid' => $member['uid'],
                                                'promotion_amount' => $pension,
                                                'order_create_time' => $order_create_time,
                                                'status' => $status,
                                                'create_at' => TIMESTAMP,
                                                'update_at' => TIMESTAMP
                                            ),
                                            1);

                                        if (1 == $status) { // 佣金可提现
                                            //DB::update('member', array('money' => $member['money'] + $promotion_amount_direct), "uid=" . $member['uid']);
                                            DB::query("UPDATE " . DB::table('member') . " SET `money` = `money` + " . $pension . " WHERE `uid` = " . $member['uid']);
                                        }
                                    }

                                }

                                // 不是VIP会员，就给上级和上上级分配佣金
                                if (0 == $vip && !empty($higher_member)) {
                                    DB::insert('pdd_order_promotion',
                                        array(
                                            'order_id' => $order_id,
                                            'p_id' => $p_id,
                                            'type' => 'higher',
                                            'p_uid' => $higher_member['uid'],
                                            'promotion_amount' => $promotion_amount_higher,
                                            'order_create_time' => $order_create_time,
                                            'status' => $status,
                                            'create_at' => TIMESTAMP,
                                            'update_at' => TIMESTAMP
                                        ),
                                        1);

                                    if (1 == $status) { // 佣金可提现
                                        //DB::update('member', array('money' => $higher_member['money'] + $promotion_amount_higher), "uid=" . $higher_member['uid']);
                                        DB::query("UPDATE " . DB::table('member') . " SET `money` = `money` + " . $promotion_amount_higher . " WHERE `uid` = " . $higher_member['uid']);
                                    }

                                    if (!empty($superior_member)) {
                                        DB::insert('pdd_order_promotion',
                                            array(
                                                'order_id' => $order_id,
                                                'p_id' => $p_id,
                                                'type' => 'superior',
                                                'p_uid' => $superior_member['uid'],
                                                'promotion_amount' => $promotion_amount_superior,
                                                'order_create_time' => $order_create_time,
                                                'status' => $status,
                                                'create_at' => TIMESTAMP,
                                                'update_at' => TIMESTAMP
                                            ),
                                            1);

                                        if (1 == $status) { // 佣金可提现
                                            //DB::update('member', array('money' => $superior_member['money'] + $promotion_amount_superior), "uid=" . $superior_member['uid']);
                                            DB::query("UPDATE " . DB::table('member') . " SET `money` = `money` + " . $promotion_amount_superior . " WHERE `uid` = " . $superior_member['uid']);
                                        }

                                        DB::insert('pdd_order_promotion',
                                            array(
                                                'order_id' => $order_id,
                                                'p_id' => $p_id,
                                                'type' => 'system',
                                                'promotion_amount' => $promotion_amount_total - $promotion_amount_direct - $promotion_amount_higher - $promotion_amount_superior,
                                                'order_create_time' => $order_create_time,
                                                'status' => $status,
                                                'create_at' => TIMESTAMP,
                                                'update_at' => TIMESTAMP
                                            ),
                                            1);
                                    } else {
                                        DB::insert('pdd_order_promotion',
                                            array(
                                                'order_id' => $order_id,
                                                'p_id' => $p_id,
                                                'type' => 'system',
                                                'promotion_amount' => $promotion_amount_total - $promotion_amount_direct - $promotion_amount_higher,
                                                'order_create_time' => $order_create_time,
                                                'status' => $status,
                                                'create_at' => TIMESTAMP,
                                                'update_at' => TIMESTAMP
                                            ),
                                            1);
                                    }
                                } else {
                                    DB::insert('pdd_order_promotion',
                                        array(
                                            'order_id' => $order_id,
                                            'p_id' => $p_id,
                                            'type' => 'system',
                                            'promotion_amount' => ($promotion_amount_total - $promotion_amount_direct),
                                            'order_create_time' => $order_create_time,
                                            'status' => $status,
                                            'create_at' => TIMESTAMP,
                                            'update_at' => TIMESTAMP
                                        ),
                                        1);
                                }
                            }
                        }
                    }
                }

                logResult('pdd_get_order', "推广位PID: " . $p_id . ", 订单编号: " . $order_sn . " 订单已经同步");

                sleep(1);
            }
        }
    }

    //////////////////////////////////////////////新的分成系统 BEGIN///////////////////////////////////////////

    public function update_pay_x($uid, $pay_id, $fee) {
        // 支付99元的用户是超级会员
        $member = DB::fetch_first("SELECT `uid`, `money`, `t_uid`, `xgroup` FROM " . DB::table('member') . " WHERE uid = " . $uid . " AND ((p_id IS NOT NULL) AND (LENGTH(p_id) > 0))");
        if (!empty($member)) {
            $xgroup = $member['xgroup'];
            if (1 == $xgroup ) { // 超级会员
                $fee_shoper = $this->SHOPER_INFO['fee_shoper'];
                if ($fee == $fee_shoper) {
                    // 超级会员升级为店主
                    $r = DB::update('member', array('xgroup' => 2, 'xgroup_time' => TIMESTAMP), array('uid' => $uid));
                    if ($r > 0) {
                        $t_uid = $member['t_uid'];
                        if (empty($t_uid)) { // 没有上级,全部给系统
                            DB::insert('x_pay_promotion',
                                array(
                                    'pay_id' => $pay_id,
                                    'type' => 'system',
                                    'promotion_amount' => $fee_shoper,
                                    'status' => 1,
                                    'create_at' => TIMESTAMP,
                                    'update_at' => TIMESTAMP
                                )
                            );
                        } else {
                            // 直属上级
                            $higher_member = DB::fetch_first("SELECT `uid`, `money`, `t_uid`, `xgroup` FROM " . DB::table('member') . " WHERE uid = " . $t_uid . " AND ((p_id IS NOT NULL) AND (LENGTH(p_id) > 0))");
                            if (!empty($higher_member)) {
                                $higher_xgroup = $higher_member['xgroup'];
                                $promotion_amount_remain = $fee_shoper;
                                if (1 == $higher_xgroup) { // 不分配奖励给直属超级会员上级，一直向上找到最近的服务经理(给这个服务经理分配86元奖励)；
                                    $nearest_servicer = $this->find_nearest_servicer($higher_member['t_uid']);
                                    if (!empty($nearest_servicer)) {
                                        $reward_new_shoper = $this->SERVICER_INFO['reward_new_shoper'];
                                        $promotion_amount_remain -= $reward_new_shoper;
                                        $type = 'new_shoper_undirect';

                                        DB::insert('x_pay_promotion',
                                            array(
                                                'pay_id' => $pay_id,
                                                'type' => $type,
                                                'p_uid' => $nearest_servicer['uid'],
                                                'promotion_amount' => $reward_new_shoper,
                                                'status' => 1,
                                                'create_at' => TIMESTAMP,
                                                'update_at' => TIMESTAMP
                                            )
                                        );

                                        DB::insert('x_money',
                                            array(
                                                'uid' => $nearest_servicer['uid'],
                                                'type' => $type,
                                                'money' => $reward_new_shoper,
                                                'org_money' => $nearest_servicer['money'],
                                                'desc' => '推荐非直属新店主奖励',
                                                'dateline' => TIMESTAMP
                                            )
                                        );

                                        //DB::update('member', array('money' => $nearest_servicer['money'] + $reward_new_shoper), "uid=" . $nearest_servicer['uid']);
                                        DB::query("UPDATE " . DB::table('member') . " SET `money` = `money` + " . $reward_new_shoper . " WHERE `uid` = " . $nearest_servicer['uid']);
                                    }
                                } else if (2 == $higher_xgroup) { // 给直属店主分配30元奖励，一直向上找到最近的服务经理(给这个服务经理分配86-30=56元奖励)
                                    $reward_new_shoper = $this->SHOPER_INFO['reward_new_shoper'];
                                    $promotion_amount_remain -= $reward_new_shoper;
                                    $type = 'new_shoper_direct';
                                    DB::insert('x_pay_promotion',
                                        array(
                                            'pay_id' => $pay_id,
                                            'type' => $type,
                                            'p_uid' => $higher_member['uid'],
                                            'promotion_amount' => $reward_new_shoper,
                                            'status' => 1,
                                            'create_at' => TIMESTAMP,
                                            'update_at' => TIMESTAMP
                                        )
                                    );

                                    DB::insert('x_money',
                                        array(
                                            'uid' => $higher_member['uid'],
                                            'type' => $type,
                                            'money' => $reward_new_shoper,
                                            'org_money' => $higher_member['money'],
                                            'desc' => '推荐直属新店主奖励',
                                            'dateline' => TIMESTAMP
                                        )
                                    );

                                    //DB::update('member', array('money' => $higher_member['money'] + $reward_new_shoper), "uid=" . $higher_member['uid']);
                                    DB::query("UPDATE " . DB::table('member') . " SET `money` = `money` + " . $reward_new_shoper . " WHERE `uid` = " . $higher_member['uid']);

                                    $nearest_servicer = $this->find_nearest_servicer($higher_member['t_uid']);
                                    if (!empty($nearest_servicer)) {
                                        $reward_new_shoper = $this->SERVICER_INFO['reward_new_shoper'] - $this->SHOPER_INFO['reward_new_shoper'];
                                        $promotion_amount_remain -= $reward_new_shoper;
                                        $type = 'new_shoper_undirect';
                                        DB::insert('x_pay_promotion',
                                            array(
                                                'pay_id' => $pay_id,
                                                'type' => $type,
                                                'p_uid' => $nearest_servicer['uid'],
                                                'promotion_amount' => $reward_new_shoper,
                                                'status' => 1,
                                                'create_at' => TIMESTAMP,
                                                'update_at' => TIMESTAMP
                                            )
                                        );

                                        DB::insert('x_money',
                                            array(
                                                'uid' => $nearest_servicer['uid'],
                                                'type' => $type,
                                                'money' => $reward_new_shoper,
                                                'org_money' => $nearest_servicer['money'],
                                                'desc' => '推荐非直属新店主奖励',
                                                'dateline' => TIMESTAMP
                                            )
                                        );

                                        //DB::update('member', array('money' => $nearest_servicer['money'] + $reward_new_shoper), "uid=" . $nearest_servicer['uid']);
                                        DB::query("UPDATE " . DB::table('member') . " SET `money` = `money` + " . $reward_new_shoper . " WHERE `uid` = " . $nearest_servicer['uid']);
                                    }

                                    // 如果这个直属店主在三级之内的店主个数达到100，而且直属店主有30个，就升级为销售经理
                                    $direct_shoper_num = $this->SALER_INFO['direct_shoper_num'];
                                    $shoper_num = $this->SALER_INFO['shoper_num'];
                                    if (($this->count_direct_shoper($higher_member['uid']) >= $direct_shoper_num)
                                        && ($this->count_3_level_shoper($higher_member['uid']) >= $shoper_num)) {
                                        DB::update('member', array('xgroup' => 3, 'xgroup_time' => TIMESTAMP), array('uid' => $higher_member['uid']));
                                    }
                                } else if (3 == $higher_xgroup) { // 给直属销售经理分配50元奖励，一直向上找到最近的服务经理(给这个服务经理分配86-50=36元奖励)
                                    $reward_new_shoper = $this->SALER_INFO['reward_new_shoper'];
                                    $promotion_amount_remain -= $reward_new_shoper;
                                    $type = 'new_shoper_direct';
                                    DB::insert('x_pay_promotion',
                                        array(
                                            'pay_id' => $pay_id,
                                            'type' => $type,
                                            'p_uid' => $higher_member['uid'],
                                            'promotion_amount' => $reward_new_shoper,
                                            'status' => 1,
                                            'create_at' => TIMESTAMP,
                                            'update_at' => TIMESTAMP
                                        )
                                    );

                                    DB::insert('x_money',
                                        array(
                                            'uid' => $higher_member['uid'],
                                            'type' => $type,
                                            'money' => $reward_new_shoper,
                                            'org_money' => $higher_member['money'],
                                            'desc' => '推荐直属新店主奖励',
                                            'dateline' => TIMESTAMP
                                        )
                                    );

                                    //DB::update('member', array('money' => $higher_member['money'] + $reward_new_shoper), "uid=" . $higher_member['uid']);
                                    DB::query("UPDATE " . DB::table('member') . " SET `money` = `money` + " . $reward_new_shoper . " WHERE `uid` = " . $higher_member['uid']);

                                    $nearest_servicer = $this->find_nearest_servicer($higher_member['t_uid']);
                                    if (!empty($nearest_servicer)) {
                                        $reward_new_shoper = $this->SERVICER_INFO['reward_new_shoper'] - $this->SALER_INFO['reward_new_shoper'];
                                        $promotion_amount_remain -= $reward_new_shoper;
                                        $type = 'new_shoper_undirect';
                                        DB::insert('x_pay_promotion',
                                            array(
                                                'pay_id' => $pay_id,
                                                'type' => $type,
                                                'p_uid' => $nearest_servicer['uid'],
                                                'promotion_amount' => $reward_new_shoper,
                                                'status' => 1,
                                                'create_at' => TIMESTAMP,
                                                'update_at' => TIMESTAMP
                                            )
                                        );

                                        DB::insert('x_money',
                                            array(
                                                'uid' => $nearest_servicer['uid'],
                                                'type' => $type,
                                                'money' => $reward_new_shoper,
                                                'org_money' => $nearest_servicer['money'],
                                                'desc' => '推荐非直属新店主奖励',
                                                'dateline' => TIMESTAMP
                                            )
                                        );

                                        //DB::update('member', array('money' => $nearest_servicer['money'] + $reward_new_shoper), "uid=" . $nearest_servicer['uid']);
                                        DB::query("UPDATE " . DB::table('member') . " SET `money` = `money` + " . $reward_new_shoper . " WHERE `uid` = " . $nearest_servicer['uid']);
                                    }

                                    // 如果这个直属销售经理在三级之内的店主个数达到1000个，而且直属店主有300个，就升级为服务经理
                                    $direct_shoper_num = $this->SERVICER_INFO['direct_shoper_num'];
                                    $shoper_num = $this->SERVICER_INFO['shoper_num'];
                                    if (($this->count_direct_shoper($higher_member['uid']) >= $direct_shoper_num)
                                        && ($this->count_3_level_shoper($higher_member['uid']) >= $shoper_num)) {
                                        DB::update('member', array('xgroup' => 4, 'xgroup_time' => TIMESTAMP), array('uid' => $higher_member['uid']));
                                    }
                                } else if (4 == $higher_xgroup) { // 给直属服务经理分配86元奖励
                                    $reward_new_shoper = $this->SERVICER_INFO['reward_new_shoper'];
                                    $promotion_amount_remain -= $reward_new_shoper;
                                    $type = 'new_shoper_direct';

                                    DB::insert('x_pay_promotion',
                                        array(
                                            'pay_id' => $pay_id,
                                            'type' => $type,
                                            'p_uid' => $higher_member['uid'],
                                            'promotion_amount' => $reward_new_shoper,
                                            'status' => 1,
                                            'create_at' => TIMESTAMP,
                                            'update_at' => TIMESTAMP
                                        )
                                    );

                                    DB::insert('x_money',
                                        array(
                                            'uid' => $higher_member['uid'],
                                            'type' => $type,
                                            'money' => $reward_new_shoper,
                                            'org_money' => $higher_member['money'],
                                            'desc' => '推荐直属新店主奖励',
                                            'dateline' => TIMESTAMP
                                        )
                                    );

                                    //DB::update('member', array('money' => $higher_member['money'] + $reward_new_shoper), "uid=" . $higher_member['uid']);
                                    DB::query("UPDATE " . DB::table('member') . " SET `money` = `money` + " . $reward_new_shoper . " WHERE `uid` = " . $higher_member['uid']);
                                }

                                // 剩下的分给系统
                                DB::insert('x_pay_promotion',
                                    array(
                                        'pay_id' => $pay_id,
                                        'type' => 'system',
                                        'promotion_amount' => $promotion_amount_remain,
                                        'status' => 1,
                                        'create_at' => TIMESTAMP,
                                        'update_at' => TIMESTAMP
                                    )
                                );

                                // 向上再找1级(直属上级的直属上级)，判断身份
                                // 如果是店主(如果这个店主三级之内的店主个数达到100，而且直属店主有30个，就升级为销售经理)
                                // 如果是销售经理(如果这个销售经理三级之内的店主个数达到1000个，而且直属店主有300个，就升级为服务经理)
                                $higher_t_uid = $higher_member['t_uid'];
                                if (!empty($higher_t_uid)) {
                                    $superior_member = DB::fetch_first("SELECT `uid`, `money`, `t_uid`, `xgroup` FROM " . DB::table('member') . " WHERE uid = " . $higher_t_uid . " AND ((p_id IS NOT NULL) AND (LENGTH(p_id) > 0))");
                                    if (!empty($superior_member)) {
                                        $superior_uid = $superior_member['uid'];
                                        $superior_xgroup = $superior_member['xgroup'];
                                        if (2 == $superior_xgroup) { // 店主是否可以升级销售经理
                                            $direct_shoper_num = $this->SALER_INFO['direct_shoper_num'];
                                            $shoper_num = $this->SALER_INFO['shoper_num'];
                                            if (($this->count_direct_shoper($superior_uid) >= $direct_shoper_num)
                                                && ($this->count_3_level_shoper($superior_uid) >= $shoper_num)) {
                                                DB::update('member', array('xgroup' => 3, 'xgroup_time' => TIMESTAMP), array('uid' => $superior_uid));
                                            }
                                        } else if (3 == $superior_xgroup) { // 销售经理是否可以升级服务经理
                                            $direct_shoper_num = $this->SERVICER_INFO['direct_shoper_num'];
                                            $shoper_num = $this->SERVICER_INFO['shoper_num'];
                                            if (($this->count_direct_shoper($superior_uid) >= $direct_shoper_num)
                                                && ($this->count_3_level_shoper($superior_uid) >= $shoper_num)) {
                                                DB::update('member', array('xgroup' => 4, 'xgroup_time' => TIMESTAMP), array('uid' => $superior_uid));
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        // 超级会员已经升级为店主，然后向下找下级，
                        // 三级之内的店主个数达到100个，而且直属店主的数量达到30个，又马上升级为销售经理
                        $direct_shoper_num = $this->SALER_INFO['direct_shoper_num'];
                        $shoper_num = $this->SALER_INFO['shoper_num'];
                        if (($this->count_direct_shoper($uid) >= $direct_shoper_num)
                            && ($this->count_3_level_shoper($uid) >= $shoper_num)) {
                            DB::update('member', array('xgroup' => 3, 'xgroup_time' => TIMESTAMP), array('uid' => $uid));
                        }

                        // 三级之内的店主个数达到1000个，而且直属店主的数量达到300个，又马上升级为服务经理
                        $direct_shoper_num = $this->SERVICER_INFO['direct_shoper_num'];
                        $shoper_num = $this->SERVICER_INFO['shoper_num'];
                        if (($this->count_direct_shoper($uid) >= $direct_shoper_num)
                            && ($this->count_3_level_shoper($uid) >= $shoper_num)) {
                            DB::update('member', array('xgroup' => 4, 'xgroup_time' => TIMESTAMP), array('uid' => $uid));
                        }
                    }
                }
            }
            /*
                超级会员支付99元，升级为店主，如果没有上级，那么不分配佣金，这99元全部给系统

                超级会员自己升级为店主
                向上找上级
                    (1) 直属上级是超级会员，
                        不分配奖励给直属超级会员上级，一直向上找到最近的服务经理(给这个服务经理分配86元奖励)；
                    (2) 直推者上级是店主(运营者)，
                        给直属店主分配30元奖励(如果这个直属店主在三级之内的店主个数达到100，而且直属店主有30个，就升级为销售经理)，一直向上找到最近的服务经理(给这个服务经理分配86-30=56元奖励)
                    (3) 直推者上级是销售经理，
                        给直属销售经理分配50元奖励(如果这个直属销售经理在三级之内的店主个数达到1000个，而且直属店主有300个，就升级为服务经理)，一直向上找到最近的服务经理(给这个服务经理分配86-50=36元奖励)
                    (4) 直推者上级是服务经理，
                        给直属服务经理分配86元奖励

                然后向上再找1级(直属上级的直属上级)，判断身份
                    如果是店主(如果这个店主三级之内的店主个数达到100，而且直属店主有30个，就升级为销售经理)
                    如果是销售经理(如果这个销售经理三级之内的店主个数达到1000个，而且直属店主有300个，就升级为服务经理)
                剩下的给系统

                超级会员升级为店主
                向下找下级，三级之内的店主个数达到100个，而且直属店主的数量达到30个，又马上升级为销售经理
                           三级之内的店主个数达到1000个，而且直属店主的数量达到300个，又马上升级为服务经理
            */
        }
    }

    public function update_order_x() {
        ignore_user_abort(); // 后台运行
        set_time_limit(0); // 取消脚本运行时间的超时上限
        ini_set('memory_limit', -1); // 不限制最大内存

        //$beginThisMonth = mktime(0,0,0,date('m'),1,date('Y'));
        //$endThisMonth = mktime(23,59,59,date('m'),date('t'),date('Y'));

        //$begin_last_90_day = time() - 90 * 24 * 3600; // 90天以内
        $begin_last_90_day = time() - 30 * 24 * 3600; // 30天以内 // modify by LiuPeng 2018-09-11
        $end_last_90_day = time();

        $start_time = date('Y-m-d', $begin_last_90_day);
        $end_time = date('Y-m-d', $end_last_90_day);

        logResult('pdd_get_order_x', "拼多多推广订单同步[BEGIN] 开始日期: " . $start_time . " 结束日期: " . $end_time);

        $members = DB::fetch_all("SELECT p_id FROM " . DB::table('member') . " WHERE (p_id IS NOT NULL) AND (LENGTH(p_id) > 0)");
        if (!empty($members)) {
            foreach ($members as $k => $v) {
                $p_id = $v['p_id'];
                $this->order_get_x($p_id, $start_time, $end_time);

                sleep(1);
            }
        }

        logResult('pdd_get_order_x', "拼多多推广订单同步[END] 开始日期: " . $start_time . " 结束日期: " . $end_time);
    }

    private function order_get_x($p_id, $start_time, $end_time) {
        $order_list = $this->ddk->get_range_order_list(
            array(
                'p_id' => $p_id,
                'start_time' => $start_time,
                'end_time' => $end_time
            )
        );

        if (!empty($order_list)) {

            /*
                订单产生的佣金分配：

                直推者自己没有上级
                不管直推者是什么身份，只要没有上级，那么订单产生的总佣金按照下面的方式分配
                    1. 直推者是超级会员 总佣金的50%给直推者，剩下的给系统
                    2. 直推者是店主(运营者) 总佣金的50%给直推者，剩下的给系统
                    3. 直推者是销售经理 总佣金的50%给直推者，剩下的给系统
                    4. 直推者是服务经理 总佣金的50%给直推者，剩下的给系统

                直推者有上级
                1. 直推者是超级会员，先找直属上级
                   判断是否是第一笔订单，订单支付金额>=15元，给直属上级奖励10元(拉新奖励);
                   总佣金的50%给直推者，把剩下50%分配给上级的最近的店主，销售经理，服务经理
                   (1) 直属上级是超级会员，剩下的50%里面拿出20%给直属上级，然后向上找，找到最近的非直属店主(还有销售经理、服务经理)上级，剩下的50%里面拿出24%给非直属店主(还有销售经理、服务经理)上级
                   (2) 直属上级是店主，剩下的50%里面拿出35%给直属上级，然后向上找，找到最近的非直属销售经理(还有服务经理)上级，剩下的50%里面拿出24%给非直属销售经理(还有服务经理)上级
                   (3) 直属上级是销售经理，剩下的50%里面拿出35%给直属上级，然后向上找，找到最近的非直属服务经理上级，剩下的50%里面拿出24%给非直属服务经理上级
                   (4) 直属上级是服务经理，剩下的50%里面拿出35%给直属上级，不再往上找上级

                2. 直推者是店主(运营者)
                    总佣金的50%给直推者
                    (1) 直推者上级是超级会员，不分配佣金
                    (2) 直推者上级是店主(运营者)，不分配佣金
                    (3) 直推者上级是销售经理，不分配佣金
                    (4) 直推者上级是服务经理，不分配佣金

                3. 直推者是销售经理
                    总佣金的50%给直推者
                    (1) 直推者上级是超级会员，不分配佣金
                    (2) 直推者上级是店主(运营者)，不分配佣金
                    (3) 直推者上级是销售经理，不分配佣金
                    (4) 直推者上级是服务经理，不分配佣金

                4. 直推者是服务经理
                    总佣金的50%给直推者
                    (1) 直推者上级是超级会员，不分配佣金
                    (2) 直推者上级是店主(运营者)，不分配佣金
                    (3) 直推者上级是销售经理，不分配佣金
                    (4) 直推者上级是服务经理，不分配佣金
            */

            foreach ($order_list as $k => $data) {
                // 直推者
                $member = DB::fetch_first("SELECT `uid`, `money`, `t_uid`, `xgroup` FROM " . DB::table('member') . " WHERE p_id = '" . $p_id . "' AND LENGTH(p_id) > 0");
                $t_uid = $member['t_uid']; // 用户的上级
                $xgroup = $member['xgroup']; // 用户的身份(超级会员，店主，销售经理，服务经理)

                $order_sn = $data['order_sn'];
                $goods_name = $data['goods_name'];
                $order_amount = $data['order_amount'];
                $order_create_time = $data['order_create_time'];
                $order_status = intval($data['order_status']);

                // 订单状态： -1 未支付; 0-已支付；1-已成团；2-确认收货；3-审核成功；4-审核失败（不可提现）；5-已经结算；8-非多多进宝商品（无佣金订单）
                // 已经结算的订单产生的佣金就可以提现了
                $status = 0; // ys_pdd_order_promotion 表中的status字段 佣金状态: -1 失效；0 等待着可以提现；1 可以提现；2 已经申请结算；3 审核成功；4 审核失败；5 已经结算
                if ($order_status >= 1) { // 已经成团，可以结算
                    $status = 1; // 可以提现
                } else if ($order_status < 0) {
                    $status = -1; // 失效
                }

                $reward_new_super_status = 0;
                if ($order_status >= 1) { // 支付了而且已经成团
                    $reward_new_super_status = 1;
                }

                $check = DB::fetch_first("SELECT `id` FROM " . DB::table('x_order_list') . " WHERE order_sn = '" . $order_sn . "'");
                if (!empty($check) && $check['id'] > 0) {
                    $data['update_at'] = TIMESTAMP;
                    DB::update('x_order_list', $data, "order_sn = '" . $order_sn . "' AND p_id = '" . $p_id . "'");

                    if ($order_status != 8) {
                        $order_id = $check['id'];

                        DB::update('x_order_promotion', array('order_status' => $order_status), "`order_id` = " . $order_id);

                        if (1 == $status) {
                            $p_members = DB::fetch_all("SELECT `p_uid`, `type`, `promotion_amount` FROM " . DB::table('x_order_promotion') . " WHERE `order_id` = " . $order_id . " AND `type` <> 'system' AND `type` <> 'new_super' AND `status` < 1");
                            if (!empty($p_members)) {
                                foreach ($p_members as $pk => $pm) {
                                    $p_uid = $pm['p_uid'];
                                    $type = $pm['type'];
                                    $promotion_amount = $pm['promotion_amount'];

                                    $p_member = DB::fetch_first("SELECT `money` FROM " . DB::table('member') . " WHERE uid = " . $p_uid);

                                    $desc = '';
                                    if ('self' == $type) {
                                        $desc = '商品' . $goods_name . '卖出获得佣金';
                                    } else if ('direct' == $type) {
                                        $desc = '直属超级会员商品' . $goods_name . '卖出获得佣金';
                                    } else if ('undirect' == $type) {
                                        $desc = '非直属超级会员商品' . $goods_name . '卖出获得佣金';
                                    } else {
                                        // FIXME
                                    }
                                    DB::insert('x_money',
                                        array(
                                            'uid' => $p_uid,
                                            'type' => $type,
                                            'money' => $promotion_amount,
                                            'org_money' => $p_member['money'],
                                            'desc' => $desc,
                                            'dateline' => TIMESTAMP
                                        )
                                    );

                                    DB::query("UPDATE " . DB::table('member') . " SET `money` = `money` + " . $promotion_amount . " WHERE `uid` = " . $p_uid);
                                }
                            }
                        }
                        DB::update('x_order_promotion', array('status' => $status, 'update_at' => TIMESTAMP), "`order_id` = " . $order_id . " AND `type` <> 'new_super' AND `status` < 1");

                        if (1 == $reward_new_super_status) {
                            $rewards = DB::fetch_first("SELECT `p_uid`, `type`, `promotion_amount` FROM " . DB::table('x_order_promotion') . " WHERE `order_id` = " . $order_id . " AND `type` = 'new_super' AND `reward_new_super_status` < 1");
                            if (!empty($rewards)) {
                                $reward_p_uid = $rewards['p_uid'];
                                $reward_type = $rewards['type'];
                                $reward_promotion_amount = $rewards['promotion_amount'];

                                $reward_member = DB::fetch_first("SELECT `money` FROM " . DB::table('member') . " WHERE uid = " . $reward_p_uid);
                                DB::insert('x_money',
                                    array(
                                        'uid' => $reward_p_uid,
                                        'type' => $reward_type,
                                        'money' => $reward_promotion_amount,
                                        'org_money' => $reward_member['money'],
                                        'desc' => '推荐新会员奖励',
                                        'dateline' => TIMESTAMP
                                    )
                                );

                                DB::query("UPDATE " . DB::table('member') . " SET `money` = `money` + " . $reward_promotion_amount . " WHERE `uid` = " . $reward_p_uid);
                            }
                        }
                        DB::update('x_order_promotion', array('status' => (1 == $reward_new_super_status) ? 1 : $status, 'reward_new_super_status' => $reward_new_super_status, 'update_at' => TIMESTAMP), "`order_id` = " . $order_id . " AND `type` = 'new_super' AND `reward_new_super_status` < 1");
                    }
                } else {
                    $data['create_at'] = TIMESTAMP;
                    $data['update_at'] = TIMESTAMP;
                    $r = DB::insert('x_order_list', $data, 1);

                    if ($order_status != 8) {
                        $order_id = $r;
                        $promotion_amount_total = $data['promotion_amount']; // 这一笔订单总的佣金，单位分
                        if (empty($t_uid) // 没有上级，不管直推者是什么身份，直推者自己分配一部分，剩下的给系统
                            || 2 == $xgroup || 3 == $xgroup || 4 == $xgroup) { // 直推者是店主、销售经理或者服务经理，自己分配一部分，剩下的给系统
                            if (1 == $xgroup) {
                                $rate_self = $this->SUPER_INFO['rate_self']; // 千分比
                            } else if (2 == $xgroup) {
                                $rate_self = $this->SHOPER_INFO['rate_self'];
                            } else if (3 == $xgroup) {
                                $rate_self = $this->SALER_INFO['rate_self'];
                            } else if (4 == $xgroup) {
                                $rate_self = $this->SERVICER_INFO['rate_self'];
                            }
                            $promotion_amount_self = $promotion_amount_total * $rate_self / 1000;
                            $promotion_amount_self = pdd_fix($promotion_amount_self / 100, 2) * 100;
                            $promotion_amount_system = $promotion_amount_total - $promotion_amount_self;

                            $type = 'self'; // 自购商品或者分享商品被别人买了，赚取佣金
                            DB::insert('x_order_promotion',
                                array(
                                    'order_id' => $order_id,
                                    'p_id' => $p_id,
                                    'type' => $type,
                                    'p_uid' => $member['uid'],
                                    'promotion_amount' => $promotion_amount_self,
                                    'order_create_time' => $order_create_time,
                                    'order_status' => $order_status,
                                    'status' => $status,
                                    'create_at' => TIMESTAMP,
                                    'update_at' => TIMESTAMP
                                )
                            );
                            DB::insert('x_order_promotion',
                                array(
                                    'order_id' => $order_id,
                                    'p_id' => $p_id,
                                    'type' => 'system',
                                    'promotion_amount' => $promotion_amount_system,
                                    'order_create_time' => $order_create_time,
                                    'order_status' => $order_status,
                                    'status' => $status,
                                    'create_at' => TIMESTAMP,
                                    'update_at' => TIMESTAMP
                                )
                            );

                            if (1 == $status) { // 佣金可提现
                                DB::insert('x_money',
                                    array(
                                        'uid' => $member['uid'],
                                        'type' => $type,
                                        'money' => $promotion_amount_self,
                                        'org_money' => $member['money'],
                                        'desc' => '商品' . $goods_name . '卖出获得佣金',
                                        'dateline' => TIMESTAMP,
                                    )
                                );
                                //DB::update('member', array('money' => $member['money'] + $promotion_amount_self), "uid=" . $member['uid']);
                                DB::query("UPDATE " . DB::table('member') . " SET `money` = `money` + " . $promotion_amount_self . " WHERE `uid` = " . $member['uid']);
                            }
                        } else if (1 == $xgroup) { // 超级会员
                            $rate_self = $this->SUPER_INFO['rate_self']; // 千分比
                            $promotion_amount_self = $promotion_amount_total * $rate_self / 1000;
                            $promotion_amount_self = pdd_fix($promotion_amount_self / 100, 2) * 100;
                            $promotion_amount_remain = $promotion_amount_total - $promotion_amount_self;

                            $type = 'self'; // 自购商品或者分享商品被别人买了，赚取佣金
                            DB::insert('x_order_promotion',
                                array(
                                    'order_id' => $order_id,
                                    'p_id' => $p_id,
                                    'type' => $type,
                                    'p_uid' => $member['uid'],
                                    'promotion_amount' => $promotion_amount_self,
                                    'order_create_time' => $order_create_time,
                                    'order_status' => $order_status,
                                    'status' => $status,
                                    'create_at' => TIMESTAMP,
                                    'update_at' => TIMESTAMP
                                )
                            );

                            if (1 == $status) { // 佣金可提现
                                DB::insert('x_money',
                                    array(
                                        'uid' => $member['uid'],
                                        'type' => $type,
                                        'money' => $promotion_amount_self,
                                        'org_money' => $member['money'],
                                        'desc' => '商品' . $goods_name . '卖出获得佣金',
                                        'dateline' => TIMESTAMP,
                                    )
                                );
                                //DB::update('member', array('money' => $member['money'] + $promotion_amount_self), "uid=" . $member['uid']);
                                DB::query("UPDATE " . DB::table('member') . " SET `money` = `money` + " . $promotion_amount_self . " WHERE `uid` = " . $member['uid']);
                            }

                            // 直属上级
                            $higher_member = DB::fetch_first("SELECT `uid`, `money`, `t_uid`, `xgroup` FROM " . DB::table('member') . " WHERE uid = " . $t_uid . " AND ((p_id IS NOT NULL) AND (LENGTH(p_id) > 0))");
                            if (!empty($higher_member)) {
                                $higher_t_uid = $higher_member['t_uid'];
                                $higher_xgroup = $higher_member['xgroup'];
                                if (1 == $higher_xgroup) {
                                    $fee_super = $this->SUPER_INFO['fee_super']; // 推荐新会员的第一笔订单的最低付款金额，单位分
                                    $reward_new_super = $this->SUPER_INFO['reward_new_super'];
                                    $rate_direct = $this->SUPER_INFO['rate_direct'];
                                } else if (2 == $higher_xgroup) {
                                    $fee_super = $this->SHOPER_INFO['fee_super'];
                                    $reward_new_super = $this->SHOPER_INFO['reward_new_super'];
                                    $rate_direct = $this->SHOPER_INFO['rate_direct'];
                                } else if (3 == $higher_xgroup) {
                                    $fee_super = $this->SALER_INFO['fee_super'];
                                    $reward_new_super = $this->SALER_INFO['reward_new_super'];
                                    $rate_direct = $this->SALER_INFO['rate_direct'];
                                } else if (4 == $higher_xgroup) {
                                    $fee_super = $this->SERVICER_INFO['fee_super'];
                                    $reward_new_super = $this->SERVICER_INFO['reward_new_super'];
                                    $rate_direct = $this->SERVICER_INFO['rate_direct'];
                                }

                                // 判断是否是第一笔订单，订单支付金额>=15元，给直属上级奖励10元(拉新奖励);
                                $check_first_order = DB::result_first("SELECT count(`id`) FROM " . DB::table('x_order_list') . " WHERE p_id = '" . $p_id . "'");
                                if (1 == $check_first_order && $order_amount >= $fee_super) {
                                    $type = 'new_super';
                                    DB::insert('x_order_promotion',
                                        array(
                                            'order_id' => $order_id,
                                            'p_id' => $p_id,
                                            'type' => $type,
                                            'p_uid' => $higher_member['uid'],
                                            'promotion_amount' => $reward_new_super,
                                            'order_create_time' => $order_create_time,
                                            'order_status' => $order_status,
                                            'status' => (1 == $reward_new_super_status) ? 1 : $status,
                                            'reward_new_super_status' => $reward_new_super_status,
                                            'create_at' => TIMESTAMP,
                                            'update_at' => TIMESTAMP
                                        )
                                    );

                                    if (1 == $reward_new_super_status) { // 第一笔订单已经支付而且已经成团
                                        DB::insert('x_money',
                                            array(
                                                'uid' => $higher_member['uid'],
                                                'type' => $type,
                                                'money' => $reward_new_super,
                                                'org_money' => $higher_member['money'],
                                                'desc' => '推荐新会员奖励',
                                                'dateline' => TIMESTAMP,
                                            )
                                        );
                                        //DB::update('member', array('money' => $higher_member['money'] + $reward_new_super), "uid=" . $higher_member['uid']);
                                        DB::query("UPDATE " . DB::table('member') . " SET `money` = `money` + " . $reward_new_super . " WHERE `uid` = " . $higher_member['uid']);
                                    }
                                }

                                // 总佣金的50%给直推者，把剩下50%分配给上级的最近的店主，销售经理，服务经理
                                // (1) 直属上级是超级会员，剩下的50%里面拿出20%给直属上级，然后向上找，找到最近的非直属店主(还有销售经理、服务经理)上级，剩下的50%里面拿出24%给非直属店主(还有销售经理、服务经理)上级
                                // (2) 直属上级是店主，剩下的50%里面拿出35%给直属上级，然后向上找，找到最近的非直属销售经理(还有服务经理)上级，剩下的50%里面拿出24%给非直属销售经理(还有服务经理)上级
                                // (3) 直属上级是销售经理，剩下的50%里面拿出35%给直属上级，然后向上找，找到最近的非直属服务经理上级，剩下的50%里面拿出24%给非直属服务经理上级
                                // (4) 直属上级是服务经理，剩下的50%里面拿出35%给直属上级，不再往上找上级

                                // 给直属上级分佣
                                $type = 'direct'; // 直属超级会员购物分佣
                                $promotion_amount_direct = ($promotion_amount_total - $promotion_amount_self) * $rate_direct / 1000;
                                $promotion_amount_direct = pdd_fix($promotion_amount_direct / 100, 2) * 100;
                                $promotion_amount_remain -= $promotion_amount_direct;
                                DB::insert('x_order_promotion',
                                    array(
                                        'order_id' => $order_id,
                                        'p_id' => $p_id,
                                        'type' => $type,
                                        'p_uid' => $higher_member['uid'],
                                        'promotion_amount' => $promotion_amount_direct,
                                        'order_create_time' => $order_create_time,
                                        'order_status' => $order_status,
                                        'status' => $status,
                                        'create_at' => TIMESTAMP,
                                        'update_at' => TIMESTAMP
                                    )
                                );
                                if (1 == $status) { // 佣金可提现
                                    DB::insert('x_money',
                                        array(
                                            'uid' => $higher_member['uid'],
                                            'type' => $type,
                                            'money' => $promotion_amount_direct,
                                            'org_money' => $higher_member['money'],
                                            'desc' => '直属超级会员商品' . $goods_name . '卖出获得佣金',
                                            'dateline' => TIMESTAMP,
                                        )
                                    );
                                    //DB::update('member', array('money' => $higher_member['money'] + $promotion_amount_direct), "uid=" . $higher_member['uid']);
                                    DB::query("UPDATE " . DB::table('member') . " SET `money` = `money` + " . $promotion_amount_direct . " WHERE `uid` = " . $higher_member['uid']);
                                }

                                // 给非直属上级(店主，销售经理，服务经理)分佣
                                if (!empty($higher_t_uid)) {
                                    $superior_member = DB::fetch_first("SELECT `uid`, `money`, `t_uid`, `xgroup` FROM " . DB::table('member') . " WHERE uid = " . $higher_t_uid . " AND ((p_id IS NOT NULL) AND (LENGTH(p_id) > 0))");
                                    if (!empty($superior_member)) {
                                        $superior_uid = $superior_member['uid'];
                                        $type = 'undirect';
                                        if (1 == $higher_xgroup) {
                                            // 向上找最近的店主
                                            $nearest_shoper = $this->find_nearest_saler($superior_uid);
                                            if (!empty($nearest_shoper)) {
                                                $rate_undirect = $this->SHOPER_INFO['rate_undirect'];
                                                $promotion_amount_undirect = ($promotion_amount_total - $promotion_amount_self) * $rate_undirect / 1000;
                                                $promotion_amount_undirect = pdd_fix($promotion_amount_undirect / 100, 2) * 100;
                                                $promotion_amount_remain -= $promotion_amount_undirect;

                                                DB::insert('x_order_promotion',
                                                    array(
                                                        'order_id' => $order_id,
                                                        'p_id' => $p_id,
                                                        'type' => $type,
                                                        'p_uid' => $nearest_shoper['uid'],
                                                        'promotion_amount' => $promotion_amount_undirect,
                                                        'order_create_time' => $order_create_time,
                                                        'order_status' => $order_status,
                                                        'status' => $status,
                                                        'create_at' => TIMESTAMP,
                                                        'update_at' => TIMESTAMP
                                                    )
                                                );
                                                if (1 == $status) { // 佣金可提现
                                                    DB::insert('x_money',
                                                        array(
                                                            'uid' => $nearest_shoper['uid'],
                                                            'type' => $type,
                                                            'money' => $promotion_amount_undirect,
                                                            'org_money' => $nearest_shoper['money'],
                                                            'desc' => '非直属超级会员商品' . $goods_name . '卖出获得佣金',
                                                            'dateline' => TIMESTAMP,
                                                        )
                                                    );
                                                    //DB::update('member', array('money' => $nearest_shoper['money'] + $promotion_amount_undirect), "uid=" . $nearest_shoper['uid']);
                                                    DB::query("UPDATE " . DB::table('member') . " SET `money` = `money` + " . $promotion_amount_undirect . " WHERE `uid` = " . $nearest_shoper['uid']);
                                                }
                                            }

                                            // 向上找最近的销售经理
                                            $nearest_saler = $this->find_nearest_saler($superior_uid);
                                            if (!empty($nearest_saler)) {
                                                $rate_undirect = $this->SALER_INFO['rate_undirect'];
                                                $promotion_amount_undirect = ($promotion_amount_total - $promotion_amount_self) * $rate_undirect / 1000;
                                                $promotion_amount_undirect = pdd_fix($promotion_amount_undirect / 100, 2) * 100;
                                                $promotion_amount_remain -= $promotion_amount_undirect;

                                                DB::insert('x_order_promotion',
                                                    array(
                                                        'order_id' => $order_id,
                                                        'p_id' => $p_id,
                                                        'type' => $type,
                                                        'p_uid' => $nearest_saler['uid'],
                                                        'promotion_amount' => $promotion_amount_undirect,
                                                        'order_create_time' => $order_create_time,
                                                        'order_status' => $order_status,
                                                        'status' => $status,
                                                        'create_at' => TIMESTAMP,
                                                        'update_at' => TIMESTAMP
                                                    )
                                                );
                                                if (1 == $status) { // 佣金可提现
                                                    DB::insert('x_money',
                                                        array(
                                                            'uid' => $nearest_saler['uid'],
                                                            'type' => $type,
                                                            'money' => $promotion_amount_undirect,
                                                            'org_money' => $nearest_saler['money'],
                                                            'desc' => '非直属超级会员商品' . $goods_name . '卖出获得佣金',
                                                            'dateline' => TIMESTAMP,
                                                        )
                                                    );
                                                    //DB::update('member', array('money' => $nearest_saler['money'] + $promotion_amount_undirect), "uid=" . $nearest_saler['uid']);
                                                    DB::query("UPDATE " . DB::table('member') . " SET `money` = `money` + " . $promotion_amount_undirect . " WHERE `uid` = " . $nearest_saler['uid']);
                                                }
                                            }

                                            // 向上找最近的服务经理
                                            $nearest_servicer = $this->find_nearest_servicer($superior_uid);
                                            if (!empty($nearest_servicer)) {
                                                $rate_undirect = $this->SERVICER_INFO['rate_undirect'];
                                                $promotion_amount_undirect = ($promotion_amount_total - $promotion_amount_self) * $rate_undirect / 1000;
                                                $promotion_amount_undirect = pdd_fix($promotion_amount_undirect / 100, 2) * 100;
                                                $promotion_amount_remain -= $promotion_amount_undirect;

                                                DB::insert('x_order_promotion',
                                                    array(
                                                        'order_id' => $order_id,
                                                        'p_id' => $p_id,
                                                        'type' => $type,
                                                        'p_uid' => $nearest_servicer['uid'],
                                                        'promotion_amount' => $promotion_amount_undirect,
                                                        'order_create_time' => $order_create_time,
                                                        'order_status' => $order_status,
                                                        'status' => $status,
                                                        'create_at' => TIMESTAMP,
                                                        'update_at' => TIMESTAMP
                                                    )
                                                );
                                                if (1 == $status) { // 佣金可提现
                                                    DB::insert('x_money',
                                                        array(
                                                            'uid' => $nearest_servicer['uid'],
                                                            'type' => $type,
                                                            'money' => $promotion_amount_undirect,
                                                            'org_money' => $nearest_servicer['money'],
                                                            'desc' => '非直属超级会员商品' . $goods_name . '卖出获得佣金',
                                                            'dateline' => TIMESTAMP,
                                                        )
                                                    );
                                                    //DB::update('member', array('money' => $nearest_servicer['money'] + $promotion_amount_undirect), "uid=" . $nearest_servicer['uid']);
                                                    DB::query("UPDATE " . DB::table('member') . " SET `money` = `money` + " . $promotion_amount_undirect . " WHERE `uid` = " . $nearest_servicer['uid']);
                                                }
                                            }
                                        } else if (2 == $higher_xgroup) {
                                            // 向上找最近的销售经理
                                            $nearest_saler = $this->find_nearest_saler($superior_uid);
                                            if (!empty($nearest_saler)) {
                                                $rate_undirect = $this->SALER_INFO['rate_undirect'];
                                                $promotion_amount_undirect = ($promotion_amount_total - $promotion_amount_self) * $rate_undirect / 1000;
                                                $promotion_amount_undirect = pdd_fix($promotion_amount_undirect / 100, 2) * 100;
                                                $promotion_amount_remain -= $promotion_amount_undirect;

                                                DB::insert('x_order_promotion',
                                                    array(
                                                        'order_id' => $order_id,
                                                        'p_id' => $p_id,
                                                        'type' => $type,
                                                        'p_uid' => $nearest_saler['uid'],
                                                        'promotion_amount' => $promotion_amount_undirect,
                                                        'order_create_time' => $order_create_time,
                                                        'order_status' => $order_status,
                                                        'status' => $status,
                                                        'create_at' => TIMESTAMP,
                                                        'update_at' => TIMESTAMP
                                                    )
                                                );
                                                if (1 == $status) { // 佣金可提现
                                                    DB::insert('x_money',
                                                        array(
                                                            'uid' => $nearest_saler['uid'],
                                                            'type' => $type,
                                                            'money' => $promotion_amount_undirect,
                                                            'org_money' => $nearest_saler['money'],
                                                            'desc' => '非直属超级会员商品' . $goods_name . '卖出获得佣金',
                                                            'dateline' => TIMESTAMP,
                                                        )
                                                    );
                                                    //DB::update('member', array('money' => $nearest_saler['money'] + $promotion_amount_undirect), "uid=" . $nearest_saler['uid']);
                                                    DB::query("UPDATE " . DB::table('member') . " SET `money` = `money` + " . $promotion_amount_undirect . " WHERE `uid` = " . $nearest_saler['uid']);
                                                }
                                            }

                                            // 向上找最近的服务经理
                                            $nearest_servicer = $this->find_nearest_servicer($superior_uid);
                                            if (!empty($nearest_servicer)) {
                                                $rate_undirect = $this->SERVICER_INFO['rate_undirect'];
                                                $promotion_amount_undirect = ($promotion_amount_total - $promotion_amount_self) * $rate_undirect / 1000;
                                                $promotion_amount_undirect = pdd_fix($promotion_amount_undirect / 100, 2) * 100;
                                                $promotion_amount_remain -= $promotion_amount_undirect;

                                                DB::insert('x_order_promotion',
                                                    array(
                                                        'order_id' => $order_id,
                                                        'p_id' => $p_id,
                                                        'type' => $type,
                                                        'p_uid' => $nearest_servicer['uid'],
                                                        'promotion_amount' => $promotion_amount_undirect,
                                                        'order_create_time' => $order_create_time,
                                                        'order_status' => $order_status,
                                                        'status' => $status,
                                                        'create_at' => TIMESTAMP,
                                                        'update_at' => TIMESTAMP
                                                    )
                                                );
                                                if (1 == $status) { // 佣金可提现
                                                    DB::insert('x_money',
                                                        array(
                                                            'uid' => $nearest_servicer['uid'],
                                                            'type' => $type,
                                                            'money' => $promotion_amount_undirect,
                                                            'org_money' => $nearest_servicer['money'],
                                                            'desc' => '非直属超级会员商品' . $goods_name . '卖出获得佣金',
                                                            'dateline' => TIMESTAMP,
                                                        )
                                                    );
                                                    //DB::update('member', array('money' => $nearest_servicer['money'] + $promotion_amount_undirect), "uid=" . $nearest_servicer['uid']);
                                                    DB::query("UPDATE " . DB::table('member') . " SET `money` = `money` + " . $promotion_amount_undirect . " WHERE `uid` = " . $nearest_servicer['uid']);
                                                }
                                            }
                                        } else if (3 == $higher_xgroup) {
                                            // 向上找最近的服务经理
                                            $nearest_servicer = $this->find_nearest_servicer($superior_uid);
                                            if (!empty($nearest_servicer)) {
                                                $rate_undirect = $this->SERVICER_INFO['rate_undirect'];
                                                $promotion_amount_undirect = ($promotion_amount_total - $promotion_amount_self) * $rate_undirect / 1000;
                                                $promotion_amount_undirect = pdd_fix($promotion_amount_undirect / 100, 2) * 100;
                                                $promotion_amount_remain -= $promotion_amount_undirect;

                                                DB::insert('x_order_promotion',
                                                    array(
                                                        'order_id' => $order_id,
                                                        'p_id' => $p_id,
                                                        'type' => $type,
                                                        'p_uid' => $nearest_servicer['uid'],
                                                        'promotion_amount' => $promotion_amount_undirect,
                                                        'order_create_time' => $order_create_time,
                                                        'order_status' => $order_status,
                                                        'status' => $status,
                                                        'create_at' => TIMESTAMP,
                                                        'update_at' => TIMESTAMP
                                                    )
                                                );
                                                if (1 == $status) { // 佣金可提现
                                                    DB::insert('x_money',
                                                        array(
                                                            'uid' => $nearest_servicer['uid'],
                                                            'type' => $type,
                                                            'money' => $promotion_amount_undirect,
                                                            'org_money' => $nearest_servicer['money'],
                                                            'desc' => '非直属超级会员商品' . $goods_name . '卖出获得佣金',
                                                            'dateline' => TIMESTAMP,
                                                        )
                                                    );
                                                    //DB::update('member', array('money' => $nearest_servicer['money'] + $promotion_amount_undirect), "uid=" . $nearest_servicer['uid']);
                                                    DB::query("UPDATE " . DB::table('member') . " SET `money` = `money` + " . $promotion_amount_undirect . " WHERE `uid` = " . $nearest_servicer['uid']);
                                                }
                                            }
                                        } else if (4 == $higher_xgroup) {
                                            // 不再往上找上级
                                        }
                                    }
                                }

                                // 剩下的佣金给系统
                                DB::insert('x_order_promotion',
                                    array(
                                        'order_id' => $order_id,
                                        'p_id' => $p_id,
                                        'type' => 'system',
                                        'promotion_amount' => $promotion_amount_remain,
                                        'order_create_time' => $order_create_time,
                                        'order_status' => $order_status,
                                        'status' => $status,
                                        'create_at' => TIMESTAMP,
                                        'update_at' => TIMESTAMP
                                    )
                                );
                            }
                        }
                    }
                }

                logResult('pdd_get_order_x', "推广位PID: " . $p_id . ", 订单编号: " . $order_sn . " 订单已经同步");

                sleep(1);
            }
        }
    }

    private function find_nearest_shoper($uid) {
        if (!empty($uid)) {
            $member = DB::fetch_first("SELECT `uid`, `money`, `t_uid`, `xgroup` FROM " . DB::table('member') . " WHERE uid = " . $uid . " AND ((p_id IS NOT NULL) AND (LENGTH(p_id) > 0))");
            if (!empty($member)) {
                if (2 == $member['xgroup']) { // 店主
                    return $member;
                } else {
                    return $this->find_nearest_shoper($member['t_uid']);
                }
            }
        }

        return false;
    }

    private function find_nearest_saler($uid) {
        if (!empty($uid)) {
            $member = DB::fetch_first("SELECT `uid`, `money`, `t_uid`, `xgroup` FROM " . DB::table('member') . " WHERE uid = " . $uid . " AND ((p_id IS NOT NULL) AND (LENGTH(p_id) > 0))");
            if (!empty($member)) {
                if (3 == $member['xgroup']) { // 销售经理
                    return $member;
                } else {
                    return $this->find_nearest_saler($member['t_uid']);
                }
            }
        }

        return false;
    }

    private function find_nearest_servicer($uid) {
        if (!empty($uid)) {
            $member = DB::fetch_first("SELECT `uid`, `money`, `t_uid`, `xgroup` FROM " . DB::table('member') . " WHERE uid = " . $uid . " AND ((p_id IS NOT NULL) AND (LENGTH(p_id) > 0))");
            if (!empty($member)) {
                if (4 == $member['xgroup']) { // 服务经理
                    return $member;
                } else {
                    return $this->find_nearest_servicer($member['t_uid']);
                }
            }
        }

        return false;
    }

    private function count_direct_shoper($uid) { // 直属店主的数量
        $count = DB::result_first("SELECT COUNT(`uid`) FROM " . DB::table('member') . " WHERE `t_uid` = " . $uid . " AND (`xgroup` = 2 AND `xgroup` = 3 AND `xgroup` = 4) AND ((p_id IS NOT NULL) AND (LENGTH(p_id) > 0))");
        return $count;
    }

    private function count_3_level_shoper($uid) { // 三级以内店主的数量
        $count = 0;

        $count += $this->count_direct_shoper($uid); // 第2级

        // 所有的直属成员
        $direct_member = DB::fetch_all("SELECT `uid` FROM " . DB::table('member') . " WHERE `t_uid` = " . $uid . " AND ((p_id IS NOT NULL) AND (LENGTH(p_id) > 0))");
        if (!empty($direct_member)) {
            foreach ($direct_member as $dk => $dv) {
                $d_uid = $dv['uid'];
                $count += $this->count_direct_shoper($d_uid); // 第3级
            }
        }

        return $count;
    }

    //////////////////////////////////////////////新的分成系统 END///////////////////////////////////////////
}